const defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g; //{{}}

function genPorps(attrs) {
    let str = ''
    for (let i = 0; i < attrs.length; i++) {
        const attr = attrs[i];
        if (attr.name === 'style') {
            let obj = {}
            attr.value.split(';').forEach(item => {
                const [key, val] = item.split(':')
                obj[key] = val
            });
            attr.value = obj
        }
        str += `${attr.name}:${JSON.stringify(attr.value)},`
    }
    // {id:"app",style:{"color":" rebeccapurple","padding":" 1px"}}
    return `{${str.slice(0, -1)}}`
}

function gen(node) {
    // 判断是否是文本
    if (node.type === 1) {
        return generate(node)
    } else {
        let text = node.text
        // 没有{{}}
        if (!defaultTagRE.test(text)) {
            return `_v(${JSON.stringify(text)})`
        }
        let tokens = []
        // 这里要重置lastIndex，因为是全局使用的
        let lastIndex = defaultTagRE.lastIndex = 0
        let match
        while (match = defaultTagRE.exec(text)) {
            let index = match.index
            // 有{{}}
            if (index > lastIndex) {
                tokens.push(JSON.stringify(text.slice(lastIndex, index)))
            }
            tokens.push(`_s(${match[1].trim()})`)
            lastIndex = index + match[0].length
        }
        if (lastIndex < text.length) {
            tokens.push(JSON.stringify(text.slice(lastIndex)))
        }
        // _v("111"+_s(cccc))
        return `_v(${tokens.join("+")})`
    }
}

function genChildren(el) {
    const children = el.children
    if (children) return children.map(child => gen(child)).join(',')
}


export function generate(el) {
    const children = genChildren(el)
    let code = `_c('${el.tag}',${el.attrs.length ? genPorps(el.attrs) : 'undefined'},${children ? children : ''})`
    return code
}